package com.TTBook.utils;


import java.io.UnsupportedEncodingException;
/**
 * 字符串的编码转换
 * @author Chris
 * Create On 2013-10-14 下午4:20:05 
 * <b>Class Description:</b><br>
 * TODO Please add your class description here
 */
public class StringEncoding
{
	 static final byte[] HEX_CHAR_TABLE = {
         (byte)'0', (byte)'1', (byte)'2', (byte)'3',
         (byte)'4', (byte)'5', (byte)'6', (byte)'7',
         (byte)'8', (byte)'9', (byte)'a', (byte)'b',
         (byte)'c', (byte)'d', (byte)'e', (byte)'f'
 };
 /**
  * 将字节序列转化为对应的十六进制字符串表示形式
  * @param raw 原始字节序列
  * @return 十六进制字符串
  * @throws UnsupportedEncodingException
  */
 public static String getHexString(byte[] raw)
         throws UnsupportedEncodingException
 {
     byte[] hex = new byte[2 * raw.length];
     int index = 0;

     for (byte b : raw)
     {
         int v = b & 0xFF;
         hex[index++] = HEX_CHAR_TABLE[v >>> 4];
         hex[index++] = HEX_CHAR_TABLE[v & 0xF];
     }
     return new String(hex, "ASCII");
 }

 /**
  * 将十六进制的形式的字符串解析为字节序列
  * @param s
  * @return
  */
 public static byte[] hexStringToByteArray(String s)
 {
	 if(s == null || s.length() < 2)
	 {
		 return new byte[0];
	 }
     int len = s.length();
     byte[] data = new byte[len / 2];
     for (int i = 0; i < len; i += 2)
     {
         data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                 .digit(s.charAt(i + 1), 16));
     }
     return data;
 }

 /**
  * 对字符串以UTF-8格式编码后再转化为十六进制格式字符串
  * @param str
  * @return
  */
 public static String encodeString(String str) throws UnsupportedEncodingException
 {
     if (str == null || str.length() == 0)
     {
         return "";
     }
     byte[] bytes = str.getBytes("UTF-8");
     return getHexString(bytes);
 }

 /**
  * 把UTF-8编码格式的十六进制字符串转化为原始字符串形式
  * @param str
  * @return
  * @throws UnsupportedEncodingException
  */
 public static String decodeString(String str) throws UnsupportedEncodingException
 {
     if (str == null || str.length() == 0)
     {
         return "";
     }
     byte[] bytes = hexStringToByteArray(str);
     return new String(bytes, "UTF-8");
 }

}
